package org.budo.sentinel.util;

import java.util.List;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;

/**
 * @author lmw
 */
public class SentinelUtil {
    public static Double flowRuleCount(String resource) {
        FlowRule flowRule = findFlowRule(resource);
        return null == flowRule ? null : flowRule.getCount();
    }

    public static FlowRule findFlowRule(String resource) {
        List<FlowRule> rules = FlowRuleManager.getRules();
        for (FlowRule rule : rules) {
            String res = rule.getResource();
            if (resource.equals(res)) {
                return rule;
            }
        }

        return null;
    }

    public static FlowRule qpsFlowRule(String resource, Double count) {
        FlowRule rule = new FlowRule();
        rule.setResource(resource);
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setCount(count);
        return rule;
    }

    public static FlowRule threadFlowRule(String resource, Double count) {
        FlowRule rule = new FlowRule();
        rule.setResource(resource);
        rule.setGrade(RuleConstant.FLOW_GRADE_THREAD);
        rule.setCount(count);
        return rule;
    }
}